package top.program.attend.service;

import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.program.attend.dao.AttendMapper;
import top.program.attend.entity.Attend;
import top.program.attend.vo.QueryCondition;
import top.program.common.page.PageQueryBean;
import top.program.common.utils.DateUtils;
import top.program.user.entity.User;

import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("attendServiceImpl")
public class AttendServiceImpl implements AttendService {

    /**
     * 中午十二点 ， 判定上下午
     */
    private static final int NOON_HOUR = 12;
    private static final int NOON_MINITE = 00;
    private Log log = LogFactory.getLog(AttendServiceImpl.class);

    @Autowired
    private AttendMapper attendMapper;
    //没有签到情况下 缺席时长
    private Integer ABSENCE_DAY = 480;
    //考勤状态  非正常 2
    private Byte ATTEND_STATUS_ABNORMAL = 2;
    //考勤状态 正常1
    private Byte ATTEND_STATUS_NORMAL;
    //早晨打卡时间
    private int MORNING_HOUR = 9;
    private int MORNING_MINUTE = 30;
    //晚上打卡时间
    private int EVENING_HOUR = 6;
    private int EVENING_MINUTE = 30;

    /**
     *@Author xcl
     *@Date 2017/10/17 0:36
     *@Description 打卡记录
     */
    @Override
    public void signAttend(Attend attend) throws Exception {
        //中午打卡之前是早晨打卡 ， 十二点打卡以后算下午打卡  检查与上午打卡时间差  并且记录缺席时间
        //早晨打卡九点半以后算异常：迟到
        //下午打卡 十八点之前 算异常
        try {
            Date today = new Date();
            attend.setAttendDate(today);
            attend.setAttendWeek((byte)DateUtils.getWake());
            Date noon = DateUtils.getDate(NOON_HOUR,NOON_MINITE);
            Date morningAttend = DateUtils.getDate(MORNING_HOUR,MORNING_MINUTE);
            Date eveningAttend = DateUtils.getDate(EVENING_HOUR,EVENING_MINUTE);

            //获取当天打卡记录
            Attend todayRecord = attendMapper.selectTodaySignRecord(attend.getUserId());
            if(today.compareTo(noon)<=0){
                //上午打卡
                if(todayRecord == null){
                    attend.setAttendMorning(today);
                    if(today.compareTo(morningAttend)>0){
                        //大于九点半迟到了
                        attend.setAttendStatus(ATTEND_STATUS_ABNORMAL);
                        attend.setAbsence(DateUtils.getMunite(morningAttend,today));
                    }
                    attendMapper.insertSelective(attend);
                }else{
                    return;
                }
            }else{
                //下午打卡
                todayRecord.setAttendEvening(today);
                if(todayRecord == null){
                    attendMapper.insertSelective(attend);
                }else{
                    if(today.compareTo(eveningAttend)<0){
                        //早于下午六点半 早退
                        todayRecord.setAttendStatus(ATTEND_STATUS_ABNORMAL);
                        todayRecord.setAbsence(DateUtils.getMunite(today,eveningAttend));
                    }else {
                        todayRecord.setAttendStatus(ATTEND_STATUS_NORMAL);
                        todayRecord.setAbsence(0);
                    }
                    attendMapper.updateByPrimaryKeySelective(todayRecord);
                }
            }
        }catch (Exception e){
            log.error("用户签到异常",e);
            throw e;
        }
    }

    @Override
    public PageQueryBean listAttend(QueryCondition queryCondition) {
        /*根据条件查询count记录数目，
        如果有数据 才去查分页数据   如果没有 不用去查
        */

        int count = attendMapper.countByCondition(queryCondition);
        PageQueryBean pageResult = new PageQueryBean();
        if(count > 0){
            pageResult.setTotalRows(count);
            pageResult.setPageSize(queryCondition.getPageSize());
            pageResult.setCurrentPage(queryCondition.getCurrentPage());
            List<Attend> attendList = attendMapper.selectAttendPage(queryCondition);
            pageResult.setItems(attendList);
        }
        return pageResult;
    }

    /**
     * @Description: 检查考勤异常数据
     * @author: xcl
     * @Param:  []
     * @Return: void
     * @Date:   15:30 2017/10/18
     */
    @Override
    @Transactional
    public void checkAttend() {

        //查询缺勤用户ID 插入打卡记录  并且设置为异常 缺勤480分钟
        List<Long> userIdList =attendMapper.selectTodayAbsence();
        if(CollectionUtils.isNotEmpty(userIdList)){
            List<Attend> attendList = new ArrayList<Attend>();
            for(Long userId:userIdList){
                Attend attend = new Attend();
                attend.setUserId(userId);
                attend.setAttendDate(new Date());
                attend.setAttendWeek((byte)DateUtils.getWake());
                attend.setAbsence(ABSENCE_DAY);
                attend.setAttendStatus(ATTEND_STATUS_ABNORMAL);
                attendList.add(attend);
            }
            attendMapper.batchInsert(attendList);
        }
        // 检查晚打卡 将下班未打卡记录设置为异常
        List<Attend> absenceList = attendMapper.selectTodayEveningAbsence();
        if(CollectionUtils.isNotEmpty(absenceList)){
            for(Attend attend : absenceList){
                attend.setAbsence(ABSENCE_DAY);
                attend.setAttendStatus(ATTEND_STATUS_ABNORMAL);
                attendMapper.updateByPrimaryKeySelective(attend);
            }
        }
    }
}
